package com.jjc.android.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.util.SparseArray
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.library.SuperButton
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.adapter.FeedbackImageAdapter
import com.jjc.android.base.BaseActivity
import com.jjc.android.entity.CommonQuestionDto
import com.jjc.android.entity.LzyResponse
import com.jjc.android.entity.MediaInfo
import com.jjc.android.entity.PageInfo
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.AndroidBug5497Workaround
import com.jjc.android.util.OssManager
import com.jjc.android.util.SimpleTextWatcher
import com.jjc.android.util.paramEx
import com.jjc.android.view.CommonKt
import com.jjc.android.view.onClick
import com.lzy.okgo.OkGo
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

class FeedBackActivity : BaseActivity(){

    override val layoutId: Int = R.layout.activity_feedback
    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val imageRecyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.imageRecyclerView) }
    private val mediaNumberText: TextView by lazy { findViewById<TextView>(R.id.mediaNumberText) }
    private val editText: EditText by lazy { findViewById<EditText>(R.id.editText) }
    private val numberText: TextView by lazy { findViewById<TextView>(R.id.numberText) }
    private lateinit var mAdapter:FeedbackImageAdapter
    private val maxLength = 200
    private val maxImageCount = 4
    private val addImageData = MediaInfo()
    private val mData:ArrayList<MediaInfo> = ArrayList()

    override fun initView(savedInstanceState: Bundle?) {
        AndroidBug5497Workaround.assistActivity(this)
        setActivityTitle(getString(R.string.feedback_txt))
        editText.addTextChangedListener(object : SimpleTextWatcher(){
            override fun afterTextChanged(s: Editable?) {
                setTextCount()
            }
        })
        mData.clear()
        mData.add(addImageData)
        imageRecyclerView.layoutManager = GridLayoutManager(this,3)
        mAdapter = FeedbackImageAdapter(mData).apply {
            setOnItemChildClickListener { _, view, position ->
                if(view.id == R.id.addImageBtn){
                    CommonKt.albumPick(this@FeedBackActivity,multipleCount = maxImageCount-getCurrentImage()){
                        mData.addAll(0,it.map {
                            MediaInfo(it.path)
                        })
                        if(getCurrentImage()>=maxImageCount){
                            mData.remove(addImageData)
                        }
                        setImageCount()
                        notifyDataSetChanged()
                    }
                }else if(view.id == R.id.deleteBtn){
                    val data = getItem(position)
                    mData.remove(data)
                    if(!mData.contains(addImageData)){
                        mData.add(addImageData)
                    }
                    setImageCount()
                    notifyDataSetChanged()
                }
            }
        }
        imageRecyclerView.adapter = mAdapter
        setTextCount()
        setImageCount()
        okBtn.onClick {
            showLoadingDialog()
            mData.filter {
                !it.isAddImageType
            }.let { images->
                if(images.isNullOrEmpty()){
                    submit(null)
                }else{
                    uploadFile(images){
                        submit(it)
                    }
                }
            }

        }
    }

    private fun submit(images:List<String>?){
        OkGo.post<LzyResponse<PageInfo<CommonQuestionDto>>>(Constants.addFormRow)
            .paramEx(mutableMapOf(
                "formheaduuid" to "79595e9b07b1497baa2a5fa6057ae27d",
                "fields" to mapOf<String,Any?>(
                    "1wlj8mtymk1ffoxh" to UserManager.userInfo().tuoTuUserId,
                    "haj7s4fmmy2y9qlt" to editText.text.toString(),
                    "lh3uyhcr7mhsdnrx" to UserManager.userInfo().mobile,
                    "qhbytc1gxuq2nzba" to images?.let { TextUtils.join(",", it) }
                )
            ),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<CommonQuestionDto>>>(){
                override fun onCallSuccess(response: LzyResponse<PageInfo<CommonQuestionDto>>) {
                    hideLoadingDialog()
                    ToastUtils.show(getString(R.string.submit_feedback_success_txt))
                    finish()
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    hideLoadingDialog()
                }
            })
    }

    private fun uploadFile(files:List<MediaInfo>,action: (List<String>?) -> Unit){
        Observable.merge(files.mapIndexed { index, image->
            Observable.create<Pair<Int,MediaInfo>> { observable->
                if(image.isRemote){
                    observable.onNext(Pair(index,image))
                    observable.onComplete()
                }else{
                    OssManager.instance.upload(this@FeedBackActivity,image.mediaPath,object :
                        OssManager.OnUploadListener {
                        override fun onSuccess(uploadPath: String, objectKey: String,imageUrl:String) {
                            image.mediaPath = imageUrl
                            image.isRemote = true
                            observable.onNext(Pair(index,image))
                            observable.onComplete()
                        }

                        override fun onFailure(error: String?) {
                            observable.onError(Throwable(error))
                            observable.onComplete()
                        }
                    })
                }
            }
        }).subscribe(object : Observer<Pair<Int, MediaInfo>> {
            val remoteImage: SparseArray<MediaInfo> = SparseArray()
            override fun onSubscribe(d: Disposable) {

            }

            override fun onNext(t: Pair<Int,MediaInfo>) {
                remoteImage.put(t.first,t.second)
            }

            override fun onError(e: Throwable) {
                handle()
            }

            override fun onComplete() {
                handle()
            }

            private fun handle(){
                val images = ArrayList<String>()
                for (i in 0 until remoteImage.size()) {
                    val image: MediaInfo = remoteImage.valueAt(i)
                    images.add(image.mediaPath)
                }
                action.invoke(images)
            }
        })
    }

    private fun getCurrentImage():Int{
        return if(mData.contains(addImageData)){
            mData.size-1
        }else{
            mData.size
        }
    }

    private fun setImageCount(){
        mediaNumberText.text = "${getCurrentImage()}/$maxImageCount"
    }

    private fun setTextCount() {
        if (TextUtils.isEmpty(editText.text)) {
            numberText.text = "0/$maxLength"
        } else {
            numberText.text = "${editText.text.toString().length}/$maxLength"
        }
        checkBtn()
    }
    private fun checkBtn(){
        okBtn.isEnabled = !editText.text.isNullOrEmpty()
    }
}